import React from 'react';
import type {UploadProps} from 'antd';
import {message, Upload} from "antd";
import {uploadFileUsingPost} from "@/services/backend/fileController";
import {LoadingOutlined, PlusOutlined} from '@ant-design/icons';
import {COS_HOST} from "@/constants";

interface Props {
  biz: string;
  onChange?: (url: string) => void;
  value?: string;
}

/**
 * 图片上传组件
 * @constructor
 */
const PictureUploader: React.FC<Props> = (props: Props) => {

  const {biz, value, onChange} = props;
  const [loading, setLoading] = React.useState<boolean>(false);

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    listType: "picture-card",
    maxCount: 1,
    showUploadList: false,
    disabled: loading,
    customRequest: async (fileObj: any) => {
      setLoading(true);
      try {
        const res = await uploadFileUsingPost({biz}, {}, fileObj.file);
        // 拼接完整的图片路径
        const fullPath = COS_HOST + res.data;
        onChange?.(fullPath ?? '') // 前端回调的图片url
        fileObj.onSuccess(res.data);
      } catch (error: any) {
        message.error("上传失败，" + error.message);
        fileObj.onError(error);
      }
      setLoading(false);
    },
  };

  /**
   * 上传按钮
   */
  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传</div>
    </button>
  );

  return (
    <Upload {...uploadProps}>
      {value ? <img src={value} alt="picture" style={{width: '100%'}}/> : uploadButton}
    </Upload>
  );
};
export default PictureUploader;
